package com.example.stack08.stack;

/**
 * 使用前后栈实现浏览器的前进后退
 * @auther lijiewei
 * @date 2021/8/19 17:40
 */
public class SampleBrowser {

    private String currentPage;
    /** 回退的栈. */
    private LinkedListBasedStack backstack;
    /** 前进的栈. */
    private LinkedListBasedStack forwardStack;

    public SampleBrowser() {
        backstack = new LinkedListBasedStack();
        forwardStack = new LinkedListBasedStack();
    }

    /**
     * 打开页面
     * @param url
     * @return
     * @author lijiewei
     * @date   2021/8/20 10:13
     */
    public void open(String url) {
        if (null != currentPage) {
            backstack.push(url);
            forwardStack.clear();;
        }
        showUrl(url, "open");
    }

    /**
     * 回退页面
     * @return
     * @author lijiewei
     * @date   2021/8/20 10:36
     */
    public String goBack() {
        if (canGoBack()) {
            forwardStack.push(currentPage);
            String backUrl = backstack.pop().getData();
            showUrl(backUrl, "goBack");
            return backUrl;
        }
        System.out.println("已经是最后一页了，不能后退");
        return null;
    }

    /**
     * 前进页面
     * @return
     * @author lijiewei
     * @date   2021/8/20 11:30
     */
    public String goForward() {
        if (canGoForward()) {
            backstack.push(currentPage);
            String forwardUrl = forwardStack.pop().getData();
            showUrl(forwardUrl, "goForward");
            return forwardUrl;
        }
        System.out.println("已经是第一页了，不能前进");
        return null;
    }

    /**
     * 是否可以前进
     * @return
     * @author lijiewei
     * @date   2021/8/20 11:22
     */
    public boolean canGoForward() {
        return forwardStack.size() > 0;
    }


    /**
     * 是否可以回退
     * @return
     * @author lijiewei
     * @date   2021/8/20 10:29
     */
    public boolean canGoBack() {
        return backstack.size() > 0;
    }

    /**
     * 显示打印url
     * @param url
     * @param prefix 前缀
     * @return
     * @author lijiewei
     * @date   2021/8/20 10:22
     */
    public void showUrl(String url, String prefix) {
        currentPage = url;
        System.out.println(prefix + "page == " + url);
    }

    /**
     * 获取当前页面
     * @return
     * @author lijiewei
     * @date   2021/8/20 11:34
     */
    public String getCurrentPage(){
        return currentPage;
    }
}
